package codec2;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.util.Random;

//客户端管道处理
public class NettyClientHander extends ChannelInboundHandlerAdapter {
    //通道就绪
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Random random = new Random();
        int i = random.nextInt(2);
        MyDataInfo.MyMessage.Builder msg = MyDataInfo.MyMessage.newBuilder();
        if (i == 0) {
            msg.setDataType(MyDataInfo.MyMessage.DataType.studentType);
            MyDataInfo.Student.Builder builder = MyDataInfo.Student.newBuilder();
            builder.setId(1);
            builder.setName("顾清寒");
            msg.setStudent(builder);
        } else {
            msg.setDataType(MyDataInfo.MyMessage.DataType.teacherType);
            MyDataInfo.Teacher.Builder builder = MyDataInfo.Teacher.newBuilder();
            builder.setId(2);
            builder.setName("伽蓝");
            msg.setTeacher(builder);
        }
        ctx.writeAndFlush(msg);
    }

    //读取事件
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        System.out.println("服务器回复信息：" + buf.toString(CharsetUtil.UTF_8));
    }
}
